<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/13
 * Time: 10:51
 */

namespace app\common\library\ali\rabittmq;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
use think\response\Json;

/******  消息生产者 *******/
class Producer
{
    protected $connection;

    protected $queue;

    protected $channel;

    protected $message;

    public function __construct()
    {
        if (config('aliAmqp.type') == 'ali') {
            $user = (new AliConfig())->getUser();

            $password = (new AliConfig())->getPassword();

        } else {
            $user = config('aliAmqp.user');
            $password = config('aliAmqp.password');
        }

        $host = config('aliAmqp.host');
        $port = config('aliAmqp.port');
        $vhost = config('aliAmqp.vhost');
        $this->connection = new AMQPStreamConnection($host, $port, $user, $password, $vhost);
        $this->channel = $this->connection->channel();
    }

    public function setQueue($queue)
    {
        $this->queue = $queue;
        $this->channel->queue_declare($queue, false, true, false, false);
    }

    /**
     * @param $msg Json 消息内容
     * @param $msg_type string 消息类型  delayed 延时消息 general 普通消息
     * @param $delayed int 消息延时时间 单位ms
     * */
    public function setMessage($msg, $msg_type = 'delayed',$delayed = 0)
    {
        switch ($msg_type) {
            case "delayed":
                $delayed = $delayed;

                $table = new AMQPTable(['delay' => $delayed]);
                $this->message = new AMQPMessage($msg, ['application_headers' => $table,'content_type' => 'text/plain', 'delivery_mode' => 2]);
                break;
            case "general":
                $this->message = new AMQPMessage($msg);
                break;
        }
    }

    /**
     * 消息生产
     * @return void
     * */
    public function basic_publish()
    {
        $this->channel->basic_publish($this->message, '', $this->queue);
    }

    public function __destruct()
    {
        $this->channel->close(); //通道关闭
        $this->connection->close(); //链接关闭
        // TODO: Implement __destruct() method.
    }


}